package com.example.myview.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import com.example.myview.R
import kotlin.random.Random

class FindMeView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val faceBitmap = ContextCompat.getDrawable(context, R.drawable.face)?.toBitmap(300,300)
    private var faceX = 0f
    private var faceY = 0f
    private val path = Path()
    private val paint = Paint().apply {
        style = Paint.Style.FILL
        color = Color.BLACK
    }
    private fun randPositions(){
        //让图形的位置随机出现，减掉图形的宽高是避免出现在屏幕外面
        faceX = Random.nextInt(width - 300).toFloat()
        faceY = Random.nextInt(height - 300).toFloat()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            faceBitmap?.let { drawBitmap(it,faceX,faceY,null) }
            drawPath(path,paint)
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.apply {
            when(action){
                MotionEvent.ACTION_DOWN ->{
                    randPositions()

                    path.reset()
                    //添加一个矩形一个矩形布满整个屏幕，方向为顺时钟方向 CW
                    path.addRect(0f,0f,width.toFloat(),height.toFloat(),Path.Direction.CW)
                    //添加一个圆形，方向为逆时钟方向 CCW。两个路径刚好消掉，形成圆孔
                    path.addCircle(x,y,250f,Path.Direction.CCW)
                }
                MotionEvent.ACTION_MOVE ->{
                    path.reset()
                    //添加一个矩形一个矩形布满整个屏幕，方向为顺时钟方向 CW
                    path.addRect(0f,0f,width.toFloat(),height.toFloat(),Path.Direction.CW)
                    //添加一个圆形，方向为逆时钟方向 CCW。两个路径刚好消掉，形成圆孔
                    path.addCircle(x,y,250f,Path.Direction.CCW)
                }
                MotionEvent.ACTION_UP ->{
                    path.reset()
                }
            }
            invalidate()
        }
        performClick()
        return true
//        return super.onTouchEvent(event)
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }
}